package Servlet;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Rollback {
	public static final String JDBC_URL="jdbc:mysql://localhost:3306/LoginTools?useUnicode=ture&characterEncoding=UTF-8&serverTimezone=UTC&allowMultiQueries=ture";
	public static final String JDBC_USER="localhost";
	public static final String JDBC_PASSWORD="123456";
	public static void main(String[] args) {
		Connection con = null;
		PreparedStatement ps = null;
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			con = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
			con.setAutoCommit(false);
			System.out.println("删除id为2的用户");
			ps = con.prepareStatement("delete from users where id = 2;");
			ps.executeUpdate();
			System.out.println("更新用户id为4的用户，注意关键字where故意写错了，模拟可能发生的异常");
			ps = con.prepareStatement("update users username = 'haha' whee id = 4");
			ps.executeUpdate();
			con.commit();
		}catch(Exception e) {
			if(con != null) {
				try {
					con.rollback();
					System.out.println("事务回滚，删除操作不会发生");
				}catch(Exception ex) {
					ex.printStackTrace();
				}
			}
			e.printStackTrace();
		}finally {
			if(ps != null) {
				try {
						ps.close();
				}catch(SQLException e) {
					e.printStackTrace();
				}
			}
			if(con != null) {
				try {
						con.close();
				}catch(SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
